<!-- src/views/History.vue -->
<template>
  <a-card title="检测历史" :bordered="false">
    <div class="search-bar">
      <a-form layout="inline">
        <a-form-item label="查询粒度">
          <a-select v-model:value="pickerMode" style="width: 120px" @change="onModeChange">
            <a-select-option value="year">按年</a-select-option>
            <a-select-option value="month">按月</a-select-option>
            <a-select-option value="date">按日</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择日期">
          <a-date-picker
            v-model:value="selectedDate"
            :picker="pickerMode"
            @change="onDateChange"
            placeholder="请选择日期"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="fetchRecords">查询</a-button>
        </a-form-item>
      </a-form>
      <a-select v-model:value="filterType" style="width: 200px" placeholder="缺陷类型" @change="onTypeChange">
        <a-select-option value="all">全部类型</a-select-option>
        <a-select-option v-for="type in defectTypes" :key="type.id" :value="type.id">
          {{ type.name }}
        </a-select-option>
      </a-select>
    </div>

    <a-table
      :columns="columns"
      :data-source="historyData"
      :pagination="pagination"
      row-key="id"
      :loading="loading"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'thumbnail'">
          <img style="min-height: 120px; min-width: 200px" :src="record.thumbnail" class="thumbnail-img" @error="onImageError(record)" />
        </template>
        <template v-if="column.key === 'result'">
          <span v-if="record.defects && record.defects.length > 0">
            <a-tag v-for="defect in record.defects" :key="defect.type" :color="getTagColor(defect.type)">
              {{ defect.type }}
            </a-tag>
          </span>
          <span v-else>
            <a-tag color="green">无缺陷</a-tag>
          </span>
        </template>
        <template v-if="column.key === 'action'">
          <a-row :gutter="24">
            <a-col :span="6"><a-button size="middle" @click="viewDetail(record)">详情</a-button></a-col>
            <a-col :span="5"><a-button size="small" type="link" @click="downloadReport(record)">报告</a-button></a-col>
            <a-col :span="10"><a-button size="small" danger @click="deleteRecord(record)">删除</a-button></a-col>
          </a-row>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  deleteUsingPost,
  listAllUsingPost,
  queryTime1UsingGet,
  queryUsingGet
} from '@/api/detectionRecordController.ts';

const router = useRouter();
const loading = ref(false);
const historyData = ref([]);
const selectedDate = ref(null);
const pickerMode = ref('date');
const filterType = ref('all');

const defectTypes = ref([
  { id: 0, name: '裂纹' },
  { id: 1, name: '夹杂物' },
  { id: 2, name: '斑点' },
  { id: 3, name: '麻面' },
  { id: 4, name: '轧入氧化皮' },
  { id: 5, name: '划痕' },
  { id: 6, name: '无缺陷' }
]);

const columns = [
  { title: '缩略图', key: 'thumbnail', width: 500 },
  { title: '检测时间', dataIndex: 'detectionTime', width: 500 },
  { title: '缺陷类型', key: 'result' },
  { title: '操作', key: 'action', width: 300 }
];

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

const getTagColor = (type) => {
  const colors = {
    '裂纹': 'red',
    '夹杂物': 'purple',
    '斑点': 'cyan',
    '麻面': 'blue',
    '轧入氧化皮': 'gray',
    '划痕': 'orange'
  };
  return colors[type] || 'blue';
};

const formatData = (records) => {
  return records.map(record => {
    const defects = record.defectTypeNames && record.defectTypeNames.length > 0
      ? record.defectTypeNames.map(type => ({ type, confidence: null }))
      : [];
    return {
      id: record.id,
      thumbnail: record.image ? `data:image/jpeg;base64,${record.image}` : '',
      detectionTime: record.detectionTime ? new Date(record.detectionTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }) : '未知',
      defects,
      sourceType: record.sourceType,
      cameraId: record.cameraId,
      userId: record.userId
    };
  });
};

const fetchRecords = async () => {
  try {
    loading.value = true;
    let params = {};
    if (selectedDate.value) {
      const date = selectedDate.value;
      params.year = date.year();
      if (pickerMode.value === 'month' || pickerMode.value === 'date') {
        params.month = date.month() + 1; // Moment 的 month 从 0 开始
      }
      if (pickerMode.value === 'date') {
        params.day = date.date();
      }
    }
    const response = await queryTime1UsingGet(params);
    historyData.value = formatData(response.data || []);
    pagination.value.total = historyData.value.length;
  } catch (error) {
    message.error('加载历史数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const onTypeChange = async () => {
  try {
    loading.value = true;
    let response;
    if (filterType.value !== 'all' && filterType.value !== 6) {
        response = await queryUsingGet({ defectId: filterType.value });
    } else {
      response = await listAllUsingPost();
    }
    const records = response.data || [];
    if(filterType.value === 6){
      records.map(record => {
        record.defectTypeNames = []
      })
    }
    historyData.value = formatData(response.data || []);
    pagination.value.total = historyData.value.length;
  } catch (error) {
    message.error('加载历史数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const onDateChange = (date) => {
  selectedDate.value = date;
};

const onModeChange = () => {
  selectedDate.value = null;
};

const deleteRecord = async (record) => {
  const res = await deleteUsingPost({ id: record.id });
  if (res) {
    await onTypeChange();
    message.success('删除成功');
  } else {
    message.error('删除失败');
  }
};

const handleTableChange = (pag) => {
  pagination.value.current = pag.current;
};

const viewDetail = (record) => {
  router.push({ name: 'DefectDetail', params: { id: record.id } });
};

const downloadReport = (record) => {
  message.info(`下载报告功能待实现，记录 ID: ${record.id}`);
};

const onImageError = (record) => {
  record.thumbnail = '';
  message.error(`记录 ${record.id} 的缩略图加载失败`);
};

onMounted(() => {
  onTypeChange(); // 初始加载全部数据
});
</script>

<style scoped>
.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.thumbnail-img {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}
</style>
